package com.xing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.Utils.Result;
import com.xing.config.JSONUtils;
import com.xing.dao.LiveAttentionDao;
import com.xing.dao.LiveRoomDao;
import com.xing.dao.LiveRoomTagDao;
import com.xing.dto.LiveRoomDTO;
import com.xing.dto.LiveRoomSaveDTO;
import com.xing.dto.LiveRoomUpdateDTO;
import com.xing.dto.SysUserDTO;
import com.xing.entity.LiveRoomEntity;
import com.xing.entity.OssEntity;
import com.xing.feign.OssFeign;
import com.xing.feign.UserFeign;
import com.xing.service.LiveRoomService;
import com.xing.user.User;
import com.xing.utils.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomDao, LiveRoomEntity> implements LiveRoomService {

    @Autowired
    private OssFeign feign;

    @Autowired
    private LiveRoomDao roomDao;
    @Autowired
    private LiveRoomTagDao roomTagDao;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private LiveAttentionDao liveAttentionDao;

    @Override
    public PageData<LiveRoomDTO> getLiveRoomByPage(Integer pageNum, Integer pageSize) {
        // TODO 这里还不确定是否需要根据某些信息对查出来的数据进行排序
        // 计算分页开始
        int pageStart = (pageNum - 1) * pageSize;
        // 调用方法查询
        List<LiveRoomDTO> liveRoomByPage = roomDao.getLiveRoomByPage(pageStart, pageSize);
        // 将拼接为字符串的标签转换为list集合
        liveRoomByPage.forEach(liveRoomDTO -> {
            if (liveRoomDTO.getTags() != null) {
                liveRoomDTO.setTagList(Arrays.stream(liveRoomDTO.getTags().split(",")).toList());
            }
            Result userById = userFeign.getUserById(liveRoomDTO.getAnchorId().toString());
            liveRoomDTO.setAnchor(JSONUtils.objParse(userById.getData(), SysUserDTO.class));
        });
        // 封装查询总数的条件
        LambdaQueryWrapper<LiveRoomEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(LiveRoomEntity.class)
                .eq(LiveRoomEntity::getDelFlag, 0);
        // 查询房间总数
        Long count = roomDao.selectCount(lambdaQueryWrapper);
        // 封装返回信息
        return new PageData<>(liveRoomByPage, count);
    }


    @Override
    public LiveRoomDTO getLiveRoomByAnchorId(Long anchorId) {
        // 封装查询条件
        LambdaQueryWrapper<LiveRoomEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(LiveRoomEntity.class)
                .eq(LiveRoomEntity::getAnchorId, anchorId)
                .eq(LiveRoomEntity::getDelFlag, 0);
        // 执行查询操作
        LiveRoomEntity liveRoomEntity = roomDao.selectOne(lambdaQueryWrapper);
        // 根据查询结果判断返回信息
        if (liveRoomEntity == null) {
            return null;
        } else {
            // 远程调用将封面id转化为url
            String url = null;
            if (liveRoomEntity.getCoverId() != null) {
                OssEntity ossEntity = BeanUtil.toBean(feign.getById(liveRoomEntity.getCoverId()).getData(), OssEntity.class);
                url = ossEntity.getUrl();
            }
            LiveRoomDTO dto = BeanUtil.toBean(liveRoomEntity, LiveRoomDTO.class);
            dto.setLiveTags(roomTagDao.getRoomTagEntityByRoomId(dto.getId()));
            SysUserDTO sysUserDTO = JSONUtils.objParse(userFeign.getUserById(String.valueOf(dto.getAnchorId())).getData(), SysUserDTO.class);
            System.out.println(sysUserDTO);
            dto.setAnchor(sysUserDTO);
            dto.setUrl(url);
            return dto;
        }
    }

    @Override
    public Result saveLiveRoom(LiveRoomSaveDTO liveRoomSaveDTO) {
        if (liveRoomSaveDTO.getAnchorId() == null) {
            return new Result().err(406, "所需信息缺失");
        }
        // 调用根据主播id查询直播间信息方法进行查询
        LiveRoomDTO liveRoomDTO = this.getLiveRoomByAnchorId(liveRoomSaveDTO.getAnchorId());
        if (liveRoomDTO != null) {
            return new Result().err(658, "该主播已有直播间，请不要重复分配");
        }
        // 判断无误后将传入对象转换为对应的实体类，执行正常插入流程
        LiveRoomEntity liveRoomEntity = BeanUtil.toBean(liveRoomSaveDTO, LiveRoomEntity.class);
        int insert = roomDao.insert(liveRoomEntity);
        if (insert < 1) {
            return new Result().err(456, "插入失败");
        } else {
            return new Result().ok("插入成功");
        }
    }

    @Override
    public Result updateLiveRoomByRoomId(LiveRoomUpdateDTO liveRoomUpdateDTO) {
        // 判断是否缺少关键信息
        if (liveRoomUpdateDTO.getId() == null) {
            return new Result().err(406, "所需信息缺失");
        }
        // 转换为对应实体类
        LiveRoomEntity liveRoomEntity = BeanUtil.toBean(liveRoomUpdateDTO, LiveRoomEntity.class);
        int update = roomDao.updateById(liveRoomEntity);
        if (update < 1) {
            return new Result().err(456, "修改失败");
        }
        return new Result().ok("修改成功");
    }

    @Override
    public Result banLiveRoomByRoomId(Long liveRoomId) {
        // 查询判断id是否有效
        LiveRoomEntity liveRoomEntity = roomDao.selectById(liveRoomId);
        if (liveRoomEntity == null) {
            return new Result().err(467, "直播间不存在");
        }
        // 对数据库进行更新，将直播间设置为禁用
        liveRoomEntity.setStatus(1);
        int update = roomDao.updateById(liveRoomEntity);
        // 根据更新结果返回信息
        if (update < 1) {
            return new Result().err(456, "禁用失败");
        }
        return new Result().ok("禁用成功");
    }

    @Override
    public Result liftBanLiveRoomByRoomId(Long liveRoomId) {
        // 查询判断id是否有效
        LiveRoomEntity liveRoomEntity = roomDao.selectById(liveRoomId);
        if (liveRoomEntity == null) {
            return new Result().err(467, "直播间不存在");
        }
        // 判断直播间是否为禁用状态
        if (liveRoomEntity.getStatus() == 0) {
            return new Result().err(488, "直播间未被封禁");
        }
        // 对数据库进行更新，将直播间解禁
        liveRoomEntity.setStatus(0);
        int update = roomDao.updateById(liveRoomEntity);
        // 根据更新结果返回信息
        if (update < 1) {
            return new Result().err(456, "解禁失败");
        }
        return new Result().ok("解禁成功");
    }

    @Override
    public Result deleteLiveRoomByRoomId(Long liveRoomId) {
        // 查询判断id是否有效
        LiveRoomEntity liveRoomEntity = roomDao.selectById(liveRoomId);
        if (liveRoomEntity == null) {
            return new Result().err(467, "直播间不存在");
        }
        // 对数据库进行更新，注销直播间
        liveRoomEntity.setDelFlag(1);
        int delete = roomDao.updateById(liveRoomEntity);
        // 根据更新结果返回信息
        if (delete < 1) {
            return new Result().err(456, "注销失败");
        }
        return new Result().ok("成功注销");
    }

    @Override
    public LiveRoomDTO getLiveRoomByRoomNumber(Long roomNumber) {
        // 封装查询条件
        LambdaQueryWrapper<LiveRoomEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(LiveRoomEntity.class)
                .eq(LiveRoomEntity::getRoomNumber, roomNumber)
                .eq(LiveRoomEntity::getDelFlag, 0);
        // 执行查询操作
        LiveRoomEntity liveRoomEntity = roomDao.selectOne(lambdaQueryWrapper);
        // 根据查询结果判断返回信息
        if (liveRoomEntity == null) {
            return null;
        } else {
            // 远程调用将封面id转化为url
            String url = null;
            if (liveRoomEntity.getCoverId() != null) {
                OssEntity ossEntity = BeanUtil.toBean(feign.getById(liveRoomEntity.getCoverId()).getData(), OssEntity.class);
                url = ossEntity.getUrl();
            }
            LiveRoomDTO dto = BeanUtil.toBean(liveRoomEntity, LiveRoomDTO.class);
            dto.setLiveTags(roomTagDao.getRoomTagEntityByRoomId(dto.getId()));
            SysUserDTO sysUserDTO = JSONUtils.objParse(userFeign.getUserById(String.valueOf(dto.getAnchorId())).getData(), SysUserDTO.class);
            dto.setAnchor(sysUserDTO);
            dto.setUrl(url);
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            dto.setIsAttention(liveAttentionDao.getIsAndAttention(user.getId().toString(), dto.getAnchorId().toString()));
            return dto;
        }
    }


}
